<template>
    <action-bar :actionBarData="actionBarData" @search="searchInfo" @clearInput="clearSearch" @addMsg="createPoemsList"></action-bar>
    <div class="switch-content f-l-r">
        <span class="active" :class="{'active-left': switchBtn == 0, 'active-right': switchBtn == 1}"></span>
        <div class="s_manager" :class="{'selection': switchBtn == 0}" @click="switchBtn = 0"><button> 管理员 </button></div>
        <div class="s_user" :class="{'selection': switchBtn == 1}" @click="switchBtn = 1"><button> 用户 </button></div>
    </div>
    <div class="poems-list">
        <el-table ref="tableRef" :data="switchBtn == 0 ? adminPoemsList : userPoemsList" style="width: 100%" max-height="250"
            @row-click="goToDetail">
            <el-table-column v-if="isDeleteBatch && switchBtn == 0" class="selection" fixed type="selection"/>
            <el-table-column class="index" fixed type="index" label="编号"/>
            <el-table-column prop="pl_name" sortable label="名称" width="200"/>
            <el-table-column prop="pl_cover" label="封面" width="200">
                <template #default="scope">
                    <div class="img-preview" style="display: flex; align-items: center" v-if="scope.row.pl_cover && scope.row.pl_cover != '无'">
                        <!-- <viewer>
                            <img :src="scope.row.pl_cover">
                        </viewer> -->
                        <div>
                            <img :src="scope.row.pl_cover">
                        </div>
                    </div>
                    <div style="display: flex; align-items: center" v-else>
                        无封面
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="pl_synopsis" label="简介"/>
            <el-table-column prop="pl_time" sortable label="创建时间" width="250"/>
            <el-table-column prop="uid" label="所属用户" width="200"/>
            <el-table-column fixed="right" width="160" label="操作" v-if="switchBtn != 1" class-name="handle-cell">
                <template #default="scope">
                    <div class="b-l_handle">
                        <!-- <div>
                            <el-switch v-model="stateList[`${ scope.row.bid }`].state" :loading="stateList[`${ scope.row.bid }`].loading" 
                                @click="changeBannerState(scope.row.bid, stateList[`${ scope.row.bid }`])"/>
                            <span v-if="stateList[`${ scope.row.bid }`].state">启用</span>
                            <span v-else>停用中</span>
                        </div> -->
                        <!-- <el-button link type="primary" size="small" @click.prevent="updataRow(scope.row)">
                            <div></div>
                            查看详情
                        </el-button> -->
                        <button class="table-fix-btn t-change-btn" @click.stop="updataRow(scope.row)">
                            <div></div>
                            更改
                        </button>
                        <button class="table-fix-btn t-delete-btn" @click.stop="deleteRow(scope.$index, scope.row)">
                            <div></div>
                            删除
                        </button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-footer">
            <div class="f-b-r" style="width: 100%;">
                <div v-if="switchBtn == 0">
                    <el-checkbox v-model="isDeleteBatch" label="批量删除" style="margin-right: 1rem;"/>
                    <el-button type="danger" class="delete-btn" @click.prevent="getDeleteData">批量删除</el-button>
                </div>
                <div class="demo-pagination-block" v-if="switchBtn == 0">
                    <el-pagination v-model:current-page="currentPage0" v-model:page-size="pageSize0" :pager-count="13"
                        :page-sizes="[10, 100, 200, 300, 400, 500, 1000]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="totalLength0"
                        @size-change="handleSizeChange('admin', pageSize0)" @current-change="handleCurrentChange('admin', currentPage0)" />
                </div>
                <div class="demo-pagination-block" v-else>
                    <el-pagination v-model:current-page="currentPage1" v-model:page-size="pageSize1" :pager-count="13"
                        :page-sizes="[10, 100, 200, 300, 400, 500, 1000]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="totalLength1"
                        @size-change="handleSizeChange('user', pageSize1)" @current-change="handleCurrentChange('user', currentPage1)" />
                </div>
            </div>
        </div>
    </div>
    <dialog-alert v-if="isdeleteAlert" :data="deleteAlertData" @on-confirm="onConfirm" @on-close="onConcel">
        <div>
            <h2>是否删除下列选中的诗歌？</h2>
            <el-table :data="deleteDate" style="width: 100%" max-height="250" class="delete-table">
                <el-table-column class="index" fixed type="index" label="编号"/>
                <el-table-column prop="pl_name" label="名称" width="100"/>
                <el-table-column prop="pl_cover" label="封面" width="250">
                    <template #default="scope">
                        <div class="img-preview" style="display: flex; align-items: center" v-if="scope.row.pl_cover && scope.row.pl_cover != '无'">
                            <viewer>
                                <img :src="scope.row.pl_cover">
                            </viewer>
                        </div>
                        <div style="display: flex; align-items: center" v-else>
                            无封面
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="pl_synopsis" label="简介"/>
                <el-table-column prop="pl_time" label="创建时间" width="100"/>
                <el-table-column prop="uid" label="所属用户" width="200"/>
            </el-table>
        </div>
    </dialog-alert>
    <!-- <create-alert v-if="isShowCreatePoemsListAlert" :type="type" :data="changeData" :searchType="searchType" :searchInput="searchInput"  -->
    <create-alert v-if="isShowCreatePoemsListAlert" :type="type" :data="changeData" @closeCreatePoemsListlAlert="closeCreatePoemsListlAlert"></create-alert>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import managePoemsListStore from '../manage-poemsList.store'
import { IPoemsListModel } from '../manage-poemsList.model'
import { ElMessage } from 'element-plus'
import { IPaginationType } from '../../manage-author/manage-author.model'
import CreateAlert from '@/page/administrator/index/page/manage-poetry/component/alert/create-poems-list.vue'
import router from '@/router'

const managePoemsListSe = managePoemsListStore()
let switchBtn = ref<number>(0) // 切换管理员/用户诗单

// 头部工具栏数据
const actionBarData = {
    addButtonMsg: '创建诗单',
    inputPlaceholder2: '按诗单名称搜索',
    inputPlaceholder3: '按账号搜索',
}
let isSearch = ref<boolean>(false) // 用于标记当前表格展示的数据是否来自于搜索
// 清空搜索框
const clearSearch = () => {
    isSearch.value = false
    isFirstSearch.value = false
    currentPage0.value = IPaginationType.minCurrentpage
    pageSize0.value = IPaginationType.minPageSize
    pageSize1.value = IPaginationType.minPageSize
    getPoemsList()
}
// 搜索
let isFirstSearch = ref<boolean>(false) // 标记是否点击了搜索框里的查询按钮，如果点击就置为true，清空currentPage和pageNum
let searchInput = ref<string>('') // 用于存储从搜索框传来的数据
let searchType = ref<string>('') // 用于存储从搜索框传来的数据
const searchInfo = (type: string, value: string) => {
    if(!isFirstSearch.value) {
        isFirstSearch.value = true
        currentPage0.value = IPaginationType.minCurrentpage
        pageSize0.value = IPaginationType.minPageSize
        currentPage1.value = IPaginationType.minCurrentpage
        pageSize1.value = IPaginationType.minPageSize
    } 
    const data = {
        pageNum0: currentPage0.value,
        pageSize0: pageSize0.value,
        pageNum1: currentPage1.value,
        pageSize1: pageSize1.value,
        searchType: type == '2' ? 'N' : 'U',
        searchText: value ? value : ''
    }
    searchType.value = type
    searchInput.value = data.searchText
    managePoemsListSe.getSearchPoemsListByNameOrUid(data).then((res: any) => {
        if(res.status == 'success') {
            isSearch.value = true
            adminPoemsList.value = res.results.admin.results
            totalLength0.value = res.results.admin.total
            userPoemsList.value = res.results.user.results
            totalLength1.value = res.results.user.total
        } else {
            ElMessage.error('搜索失败！')
        }
    })
}

// 获取诗单信息
let adminPoemsList = ref<IPoemsListModel[]>([])
let userPoemsList = ref<IPoemsListModel[]>([])
let totalLength0 = ref<number>(0)
let totalLength1 = ref<number>(0)
const getPoemsList = () => {
    if(isFirstSearch.value) {
        isFirstSearch.value = false
        currentPage0.value = IPaginationType.minCurrentpage
        pageSize0.value = IPaginationType.minPageSize
        currentPage1.value = IPaginationType.minCurrentpage
        pageSize1.value = IPaginationType.minPageSize
    }
    const data = {
        pageNum0: currentPage0.value,
        pageSize0: pageSize0.value,
        pageNum1: currentPage1.value,
        pageSize1: pageSize1.value
    }
    managePoemsListSe.getPoemsList(data).then((res: any) => {
        if(res.status = 'success') {
            adminPoemsList.value = res.results.admin.results
            totalLength0.value = res.results.admin.total
            userPoemsList.value = res.results.user.results
            totalLength1.value = res.results.user.total
        }
    })
}
onMounted(() => {
    getPoemsList()
})

// 分页逻辑
let tableRef = ref<any>(null)
const currentPage0 = ref(IPaginationType.minCurrentpage) // 当前页码
const currentPage1 = ref(IPaginationType.minCurrentpage) // 当前页码
const pageSize0 = ref(IPaginationType.minPageSize1) // 每页数据条数
const pageSize1 = ref(IPaginationType.minPageSize1) // 每页数据条数
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (type: string, val: number) => {
    if(type == 'admin') {
        pageSize0.value = val
    } else {
        pageSize1.value = val
    }
    if(isSearch.value) {
        searchInfo(searchType.value, searchInput.value)
    } else {
        getPoemsList()
    }
}
const handleCurrentChange = (type: string, val: number) => {
    if(type == 'admin') {
        currentPage0.value = val
    } else {
        currentPage1.value = val
    }
    if(isSearch.value) {
        searchInfo(searchType.value, searchInput.value)
    } else {
        getPoemsList()
    }
    tableRef.value.setScrollTop(0)
}

// 更改
let type = ref<string>('')
let changeData = ref({})
const updataRow = (val: any) => {
    console.log('val', val)
    type.value = 'change'
    changeData.value = val
    isShowCreatePoemsListAlert.value = true
}

// 删除
// 批量删除
let isDeleteBatch = ref<boolean>(false)
const deleteBatch = () => {
    isDeleteBatch.value = !isDeleteBatch
}
let deleteDate = ref<any>([])
let isdeleteAlert = ref<boolean>(false)
let deleteIndex = ref<number>(-1) // 当前删除的轮播图的索引
const deleteRow = (index: number, value: any) => {
    isdeleteAlert.value = true
    deleteIndex.value = index
    deleteDate.value = [value]
}
// 获取选中需要删除的数据
const getDeleteData = () => {
    deleteDate.value = tableRef.value.getSelectionRows()
    if(deleteDate.value.length < 1) {
        ElMessage({
            showClose: true,
            message: '请先选择需要删除的数据！',
            type: 'warning',
        })
        return
    }
    isdeleteAlert.value = true
}

// 询问用户是否删除弹窗
// 弹窗数据
const deleteAlertData = computed(() => {
    return {
        title: '删除诗单信息',
        message: '',
        confirmTitle: '删除',
        isShowCancleBtn: true,
        cancleTitle: '取消',
        isShowClose: true,
        size: 'large'
    }
})
// 取消删除
const onConcel = () => {
    isdeleteAlert.value = false
} 
// 确认删除
const onConfirm = () => {
    let plidString = ''
    console.log( deleteDate.value)
    deleteDate.value.forEach((item: any, index: any) => {
        if(index == deleteDate.value.length - 1) {
            plidString += `${item.pl_id}`
        }  else {
            plidString += `${item.pl_id},`
        }
    })
    const data = {
        pl_id: plidString
    }
    managePoemsListSe.getDeletePoemsListById(data).then((res: any) => {
        if(res.status == 'success') {
            isdeleteAlert.value = false
            if(isSearch.value) {
                searchInfo(searchType.value, searchInput.value)
            } else {
                getPoemsList()
            }
            ElMessage({
                showClose: true,
                message: '删除成功！',
                type: 'success',
            })
        } else {
            ElMessage.error('删除失败！')
        }
    })
} 

// 创建新的诗单
let isShowCreatePoemsListAlert = ref<boolean>(false)
// 打开创建诗单弹窗
const createPoemsList = () => {
    type.value = 'create'
    isShowCreatePoemsListAlert.value = true
}
// 关闭创建诗单弹窗
const closeCreatePoemsListlAlert = () => {
    type.value = ''
    isShowCreatePoemsListAlert.value = false
    getPoemsList()
}

// 跳转诗单详情
const goToDetail = (value: any) => {
    console.log(value)
    router.push({
        name: 'managePoemsListDetail',
        params: {
            plId: value.pl_id
        }
    })
}
</script>

<style lang="less" scoped>
.switch-content {
    height: max-content;
    width: max-content;
    margin-top: 1rem;
    background-color: var(--pc-bg-white);
    border-radius: 0.5rem;
    cursor: pointer;
    position: relative;
    .s_manager {
        border-radius: 0.5rem 0 0 0.5rem;
    }
    .s_user {
        border-radius: 0rem 0.5rem 0.5rem 0rem;
    }
    button {
        border: 0;
        font-size: 16px;
        background-color: transparent;
        text-align: center;
        color: var(--pc-font-black);
        transition: all 0.5s;
    }
    .s_manager, .s_user {
        width: 3rem;
        height: 100%;
        padding: 0.5rem 2rem;
        text-align: center;
        z-index: 99;
    }
    .active {
        width: calc(3rem + 2rem * 2);
        height: 100%;
        position: absolute;
        top: 0;
        background-color: var(--pc-button);
        transition: all 0.5s;
        z-index: 1;
    }
    .active-left {
        left: 0;
        border-radius: 0.5rem 0 0 0.5rem;
    }
    .active-right {
        left: 7rem;
        border-radius: 0rem 0.5rem 0.5rem 0rem;
    }
    .selection {
        button {
            color: var(--pc-font-white) !important;
        }
    }
}
.poems-list {
    width: 100%;
    background-color: var(--pc-bg-white);
    margin-top: 0.5rem;
    border-radius: 0.5rem;
    padding: 1rem 0;
    padding-top: 0rem !important;
    flex: 1;
    background-color: var(--pc-bg-white);
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    :deep(.el-table) {
        tbody {
            .cell {
                height: 4rem;
                -webkit-line-clamp: 3;
            }
        }
    }
}
</style>